<template>
  <div>
    <a-row style="background: #fff" :gutter="[0, 0]">
      <div class="conditionsSearch">条件搜索</div>
      <div class="search-wrapper">
        <!-- 头部搜索 -->

        <a-form-model
          class="topAntform"
          ref="searchFormRef"
          :model="searchFormData"
        >
          <a-form-model-item label="角色名称:" class="serach-input">
            <a-input
              placeholder="请输入"
              size="large"
              v-model="searchFormData.name"
            />
          </a-form-model-item>
        </a-form-model>
        <!-- 按钮组 -->
        <div class="btn-group">
          <a-button
            type="success"
            icon="search"
            @click="searchBtnClick"
            style="background-color: #0079fe; color: #fff"
          >
            查询
          </a-button>
          <!-- <a-button @click="resetBtnClick">重置</a-button> -->
        </div>
      </div>

      <a-col>
        <a-card :body-style="{ padding: '10px' }" :bordered="false">
          <div
            style="
              display: flex;
              align-items: center;
              justify-content: center;
              width: 100%;
              height: 30px;
              float: right;
              margin-bottom: 10px;
              justify-content: space-between;
            "
          >
            <span
              style="
                padding-left: 12px;
                color: rgba(0, 0, 0, 0.85);
                font-size: 14px;
              "
              >当前有<span style="padding: 0 3px">{{ tableData.length }}</span
              >条数据</span
            >
            <div style="text-align: right; cursor: pointer" class="handle">
              <!-- <a
                href="javascript:;"
                style="margin: 0 10px 0 0"
                @click="addResourceHandle"
                >新增</a
              > -->
              <!-- <a class="addStyle" style="margin-right: 8px;color:#fff;" @click="addResourceHandle" v-permission:role="['add']">
                  <a-icon type="plus"/>新增
                </a> -->
            </div>
          </div>
          <div style="margin-top: 40px">
            <a-table
              :columns="columns"
              :data-source="tableData"
              :pagination="pagination"
              size="small"
            >
              <template slot="operation" slot-scope="text, record, index">
                <div class="editable-row-operations">
                  <a
                    v-if="showMember"
                    href="javascript:;"
                    style="margin: 0 10px"
                    @click="CyHandle(text, record, index)"
                    v-permission:roleUser="['memberManage']"
                  >
                    成员管理</a
                  >
                  <a
                    href="javascript:;"
                    style="margin: 0 10px 0 0"
                    @click="QxHandle(text, record, index)"
                    v-permission:roleUser="['authManage']"
                    >权限管理</a
                  >
                </div>
              </template>
            </a-table>
          </div>
        </a-card>
      </a-col>
    </a-row>
    <!-- 权限分配抽屉对话框 -->
    <a-drawer
      :headerStyle="{ borderBottom: 'none', height: '80px', color: '#666' }"
      width="40%"
      :visible="visible"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      @close="visible = false"
    >
      <span slot="title" style="color: #72767b">权限分配</span>
      <div style="height: 60px; line-height: 60px">
        <span style="font-size: 16px; color: #000">权限设置</span>
        <a-button
          class="saveBtn"
          type="success"
          @click="saveBtn"
          :loading="saveBtnLoading"
          style="
            background-color: #ff4949;
            color: #fff;
            float: right;
            margin-top: 15px;
            border: none;
          "
          >保存</a-button
        >
      </div>
      <a-spin size="large" :spinning="LoadingFlag" tip="Loading...">
        <div class="button-group">
          <a-button
            :class="{
              activeButton: buttonIndex == 0,
              deactiveButton: buttonIndex !== 0,
            }"
            @click="btnGroupClick(0)"
            style="background-color: #0079fe; color: #fff"
            >PC</a-button
          >
          <a-button
            :class="{
              activeButton: buttonIndex == 1,
              deactiveButton: buttonIndex !== 1,
            }"
            @click="btnGroupClick(1)"
            style="background-color: #0079fe; color: #fff"
            >APP</a-button
          >
          <a-button
            :class="{
              activeButton: buttonIndex == 2,
              deactiveButton: buttonIndex !== 2,
            }"
            @click="btnGroupClick(2)"
            style="background-color: #0079fe; color: #fff"
            >公众号</a-button
          >
        </div>

        <div style="min-height: 200px">
          <a-tree
            style="margin: 10px 30px"
            v-model="checkedKeys"
            checkable
            :replaceFields="replaceFields"
            :expanded-keys="expandedKeys"
            :auto-expand-parent="autoExpandParent"
            :selected-keys="selectedKeys"
            :tree-data="treeData"
            @expand="onExpand"
            @select="onSelect"
            @check="onCheck"
          />
        </div>
      </a-spin>
    </a-drawer>
  </div>
</template>

<script>
import {
  queryListTreeA,
  queryListTreeB,
  getRoleList,
  roleDelete,
  roleSave,
  roleUpdate,
  //  queryRoleListByUserAccIdA,
  saveRoleListByRoleId,
} from "../../services/system";
export default {
  name: "MenuManage",
  data() {
    return {
      searchFormData: {
        name: "",
      },
      showMember: true,
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: [],
      treeData: [],
      LoadingFlag: false,
      titleAll: "权限分配",
      tilteContent: "",
      appList: [],
      channelList: [],
      query: {
        appInfoCode: null,
        channelType: null,
      },

      replaceFields: {
        title: "name",
        key: "id",
        children: "children",
      },
      roleType: "",
      visible: false,
      confirmLoading: false,
      parentObj: {},
      menuObj: {
        name: null,
        code: null,
        remark: null,
        tenantCode: sessionStorage.getItem("tenantCode"),
      },
      rules: {
        name: [{ required: true, message: "不能为空", trigger: "blur" }],
        code: [{ required: true, message: "不能为空", trigger: "blur" }],
      },
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
      },
      columns: [
        {
          title: "角色名称",
          dataIndex: "name",
        },
        {
          title: "角色编号",
          dataIndex: "code",
        },
        {
          title: "成员人数",
          dataIndex: "userNumber",
        },
        {
          title: "创建时间",
          dataIndex: "createTime",
        },
        {
          title: "创建人",
          dataIndex: "loginName",
        },
        {
          title: "备注",
          dataIndex: "remark",
        },
        {
          title: "操作",
          dataIndex: "Action",
          scopedSlots: { customRender: "operation" },
        },
      ],
      tableData: [],
      // 选项卡按钮选择索引
      buttonIndex: 0,
      // 角色id
      roleId: "",
      // 点击保存按钮发给后台的权限数据
      finalArray: [],
      // 保存按钮状态
      saveBtnLoading: false,
    };
  },
  created() {
    this.getRoleList();
  },

  watch: {
    checkedKeys(val) {
      console.log("onCheck", val);
    },
  },

  methods: {
    onExpand(expandedKeys) {
      console.log("onExpand", expandedKeys);
      // if not set autoExpandParent to false, if children expanded, parent can not collapse.
      // or, you can remove all expanded children keys.
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    onCheck(checkedKeys, e) {
      this.finalArray = [];
      this.checkedKeys = checkedKeys;
      console.log(this.checkedKeys);
      console.log(e);
      this.finalArray.push(...this.checkedKeys);
      this.finalArray.push(...e.halfCheckedKeys);
      // console.log(this.finalArray);
    },
    onSelect(selectedKeys, info) {
      console.log("onSelect", info);
      // this.selectedKeys = selectedKeys;
    },

    // 终端选项点击响应事件
    btnGroupClick(index) {
      this.LoadingFlag = true;
      this.buttonIndex = index;
      let type = "";
      if (index == 0) {
        type = "PC";
      }
      if (index == 1) {
        type = "APP";
      }
      if (index == 2) {
        type == "WeChat";
      }
      const parmas = {
        roleId: this.roleId,
        channelType: type,
        tenantCode:
          sessionStorage.getItem("roleType") == "PLATFORM_ADMIN"
            ? ""
            : sessionStorage.getItem("tenantCode"),
        //  tenantCode:sessionStorage.getItem('tenantCode')
      };
      // 请求资源树
      queryListTreeA(parmas).then((res) => {
        this.LoadingFlag = false;
        this.treeData = res.data.data;
      });
      // 请求选中的结点数据
      const parmas2 = {
        roleId: this.roleId,
        channelType: type,
        tenantCode:
          sessionStorage.getItem("roleType") == "PLATFORM_ADMIN"
            ? ""
            : sessionStorage.getItem("tenantCode"),
        //  tenantCode:sessionStorage.getItem('tenantCode')
      };
      queryListTreeB(parmas2).then((res) => {
        console.log(res);
        this.checkedKeys = [];
        res.data.data.forEach((item) => {
          this.checkedKeys.push(item.id);
        });
      });
    },

    getRoleList() {
      if (sessionStorage.getItem("roleType") !== "PLATFORM_ADMIN") {
        // spkart
        this.roleType = "NORMAL";
      } else {
        this.roleType = "TENTANT_ADMIN";
        this.showMember = false;
      }
      const parma = {
        roleType: this.roleType,
        tenantCode: sessionStorage.getItem("tenantCode"),
        shield: 0,
      };
      getRoleList(parma).then((res) => {
        this.tableData = res.data.data.rows;
      });
    },
    handleOk() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.confirmLoading = true;
          let handle;
          if (this.menuObj.id) {
            handle = roleUpdate(this.menuObj.id, this.menuObj);
          } else {
            handle = roleSave(this.menuObj);
          }
          handle
            .then((res) => {
              this.confirmLoading = false;
              if (res.data.status == 0) {
                this.visible = false;
                this.getRoleList();
              }
            })
            .catch((error) => {
              console.log(error);
              this.confirmLoading = false;
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    addResourceHandle() {
      this.visible = true;
      this.titleAll = "新增";
    },
    CyHandle(text, item) {
      //成员管理
      console.log(item);
      this.$router.push({
        path: "mumberManage",
        query: { id: item.id, initFlag: item.initFlag },
      });
      //this.$router.push("/system/mumberManage");
    },

    QxHandle(text, item) {
      this.confirmLoading = true;

      // 保存角色id
      this.roleId = item.id;
      this.visible = true;
      this.buttonIndex = 0;
      const parmas = {
        roleId: item.id,
        channelType: "PC",
        tenantCode:
          sessionStorage.getItem("roleType") == "PLATFORM_ADMIN"
            ? ""
            : sessionStorage.getItem("tenantCode"),
        userType: sessionStorage.getItem("roleType"),
        //  tenantCode:sessionStorage.getItem('tenantCode')
      };
      // 请求资源树
      this.LoadingFlag=true
      queryListTreeA(parmas).then((res) => {
        this.LoadingFlag=false
        this.treeData = res.data.data;
      });
      // 请求选中的结点数据
      const parmas2 = {
        roleId: item.id,
        channelType: "PC",
        tenantCode:
          sessionStorage.getItem("roleType") == "PLATFORM_ADMIN"
            ? ""
            : sessionStorage.getItem("tenantCode"),
        //  tenantCode:sessionStorage.getItem('tenantCode')
      };
      queryListTreeB(parmas2).then((res) => {
        console.log(res);
        this.checkedKeys = [];
        res.data.data.forEach((item) => {
          this.checkedKeys.push(item.id);
        });
      });
      // queryRoleListByUserAccIdA(
      //   item.id,
      //   sessionStorage.getItem("tenantCode")
      // ).then((res) => {
      //   this.treeData = res.data.data.allRoleList;
      //   this.checkedKeys = res.data.data.selectRoleList;
      // });
    },

    deleteResourceHandle(text, item) {
      let vm = this;
      this.$confirm({
        title: "您确定要删除该数据？",
        content: "数据删除后不可恢复",
        onOk() {
          return new Promise((resolve, reject) => {
            roleDelete(item.id).then((res) => {
              if (res.data.status == 0) {
                vm.getRoleList();
                resolve();
              } else {
                reject(res.data.msg);
              }
            });
          });
        },
        onCancel() {},
      });
    },
    //搜索
    searchBtnClick() {
      const parma = {
        roleType: this.roleType,
        name: this.searchFormData.name,
        tenantCode: sessionStorage.getItem("tenantCode"),
      };
      getRoleList(parma).then((res) => {
        this.tableData = res.data.data.rows;
      });
    },

    saveBtn() {
      this.saveBtnLoading = true;
      saveRoleListByRoleId({
        roleId: this.roleId,
        channelType:
          this.buttonIndex == 0
            ? "PC"
            : this.buttonIndex == 1
            ? "APP"
            : "WeChat",
        resourceIds: this.finalArray,
      }).then((res) => {
        console.log(res);
        this.saveBtnLoading = false;
        this.visible = false;
        // this.$notification.open({
        //   message: '温馨提示',
        //   description:'保存权限成功'
        // });
      });
    },
  },
};
</script>

<style lang="less" scoped>
.conditionsSearch {
  border: 1px solid #eee;
  color: rgba(0, 0, 0, 0.85);
  font-size: 14px;
  padding: 6px 12px;
  border-radius: 4px 4px 0 0;
  margin: 15px 10px 0;
}
.search-wrapper {
  border-radius: 0 0 4px 4px;
  display: flex;
  background-color: #fff;
  align-items: center;
  border: 1px solid #eee;
  border-top: none;
  padding-left: 12px;
  padding-bottom: 8px;
  margin: 0 10px;
}
.topAntform {
  width: 313px;
  height: 48px;
}
.serach-input {
  display: flex;
  padding-top: 5px;
  input {
    margin-left: 10px;
    height: 30px;
  }
}
.btn-group {
  padding: 0;
  button {
    background-color: #fff !important;
    color: #666 !important;
  }
}
/deep/ .ant-card {
  padding-top: 0;
}
.addStyle {
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgb(0, 121, 254);
  width: 78px;
  height: 30px;
}
.menu {
  .handle {
    i {
      margin: 0 10px;
      font-size: 16px;
      cursor: pointer;
    }
  }
}
.button-group {
  margin-top: 24px;
  display: flex;
  justify-content: space-around;
  button {
    width: 130px;
    height: 35px;
    border-radius: 6px;
  }
  .activeButton {
    background-color: #409eff !important;
    color: #fff !important;
    outline-color: #409eff;
  }
  .deactiveButton {
    color: #409eff !important;
    border: 1px solid #409eff !important;
    background-color: #fff !important;
  }
}
.saveBtn:hover {
  background-color: #fd8484 !important;
}
</style>
